<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    
    <%@ page import="no.ntnu.tdt4237.*" %>
    <%@page import="no.ntnu.tdt4237.helperactions.*"%>
    <%@page import="java.util.regex.*"%>
    <%@ taglib prefix="tags" tagdir="/WEB-INF/tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<tags:header title=" - Register"></tags:header>


<body>
<%
String errormessage = "";
boolean registerSuccess = false;
boolean register = request.getParameter("Password") !=null;

if (register) {

	//Set the email pattern string
	Pattern p = Pattern.compile("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}\\b");
	//Match the given string with the pattern
	Matcher m = p.matcher(request.getParameter("Email"));
	boolean flawless = true;
	
	if (Database.getUser(request.getParameter("UserName")) != null){
		// The user doesn't exist
		errormessage += "<p>Username already in use!<p/>";
		flawless = false;
	}
	if(request.getParameter("UserName").length() < 4 ){
		errormessage += "<p>Username length must be 4 characters or longer</p>";
		flawless = false;
	} 
	if(request.getParameter("Password").length() < 6 ){
		errormessage += "<p>Password length must be 6 characters or longer</p>";
		flawless = false;
	} 
	if(request.getParameter("FirstName").length() < 2 ){
		errormessage += "<p>First name must be 2 letters or longer</p>";
		flawless = false;
	} 
	if(request.getParameter("LastName").length() < 2 ){
		errormessage += "<p>Last name must be 2 letters or longer</p>";
		flawless = false;
	} 
	if(!m.matches()){
		errormessage += "<p>Not a valid email address<p/>";
		flawless = false;
	}
	
	if(flawless) {
		registerSuccess = Database.saveUser(new User(request.getParameter("UserName"), 
							   request.getParameter("Password"), 
							   request.getParameter("Email"),
							   request.getParameter("FirstName"),
							   request.getParameter("LastName")));
	}
}

if (registerSuccess) {
	Activation.createAccount(request.getParameter("UserName"), request.getParameter("Email"));
	%>
		<tags:message message="Check your email!"></tags:message>
		<a href="login.jsp">Login</a>
	<%
}
else
{

	%>
		
	<tags:error errorMsg="<%=errormessage %>"></tags:error>
	
	<div class="LoginBox">
		<form action="register.jsp" method="post">
			<span>First Name:</span><input type="text" name="FirstName"></input><br/>
			<span>Last Name:</span><input type="text" name="LastName"></input><br/>
			<span>Email address:</span><input type="text" name="Email"></input><br/>
			<span>User Name:</span><input type="text" name="UserName"></input><br/>
			<span>Password:</span><input type="password" name="Password"></input><br/>
			<input type="submit" value="Register"></input>
		</form>
	</div>
	<%
}
%>


</body>
</html>